const nest = (items, id = null, cid = 'id' , pid = 'parentId') =>
    items
    .filter(item => item[pid] === id)
    .map(item => ({ ...item, children: nest(items, item[cid], cid, pid) }));

const getChildDepartmentsIds = (data, id) => {
    let ids = [];
    const loop = (data,pIds) => {
        const children = data.filter(f=> pIds.includes(f.parentId)).map(v=> v.id);
        if(children.length > 0 ){
            ids = [].concat(ids,children);
            loop(data,children)
        }
    }
    loop(data,[id])
    return ids;
}

module.exports = {
    nest,
    getChildDepartmentsIds
};